//
//  Test_API.swift
//  MZTool_Example
//
//  Created by gby on 2023/2/13.
//  Copyright © 2023 CocoaPods. All rights reserved.
//

import Foundation
import HandyJSON
import SwiftyJSON
import MZTool


struct TestApiPlugintype: MZPluginType{
    
    func process(_ result: Result<MZApiResponse, MZError>, target: MZApiRequest) -> Result<MZApiResponse, MZError> {
        switch result {
        case .success(let response):
            
            let json = JSON(response.data)
            MZ.printLog(json)
            let status : Any? = json.dictionaryValue["Status"]
            let logout : Int = json["Data"].int ?? 200
            if logout == 401 {
                //TOKEN 失效
                let customerror = NSError.init(domain: "customError", code: 403, userInfo: [NSLocalizedDescriptionKey:json["Message"].string ?? ""])
                return .failure(MZError.underlying(customerror, nil))
            }
            if status != nil, json["Status"].boolValue == false{
                let customerror = NSError.init(domain: "customError", code: 403, userInfo: [NSLocalizedDescriptionKey:json["Message"].string ?? ""])
                return .failure(MZError.underlying(customerror, nil))
            }else{
                return result
            }
        case let .failure(error):
            MZ.printLog(error)
            return .failure(error)
        }
    }
}


enum TestApi {
    case getlist( _ params: [String: Any])

}

extension TestApi: MZApiRequest {
    
    public static let sharedProvidor = MZApi<TestApi>(plugins: [TestApiPlugintype()])
    
    var baseURL: URL{
        return URL(string: "https://player2.srsztwl.cn")!
    }
    
    var path: String {
        switch self {
        case .getlist:
            return "/PlayerUser/GetAgentAnchor"
        }
    }
    
    var method: MZMethod {
        return .post
    }
    
    var headers: [String : String]? {
        return [
            "Content-type" : "application/x-www-form-urlencoded; charset=utf-8",
            "AppToken":"CfDJ8Lh85Lec_GNEsiS5qKCvBkeOBFU4y5v8zStRuJRGOupjAW_0LMkQOC-DD_RKtLtgn8096k7xFKLEo1hwqFW0waRDaxusshj3qpyXL-S3wHBQ2pyv-oTiKi9nNiULyAgouqhAcgJezUDiNOGOBF7dc76Odgu4YJLDABH-j7WHBFP-"
        ]
    }
    
    var task: MZTask {
        switch self {
        case .getlist(let par):
            return .requestParameter(parameters: par, encoding: MZURLEncoding.httpBody)
        }
    }
    
    
    
}
